package problems;
import static lib.MathLib.factorial;

/**
 * 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
 * Find the sum of all numbers which are equal to the sum of the factorial of their digits.
 * Note: as 1! = 1 and 2! = 2 are not sums they are not included.
 * 
 * @author laszlo
 *
 */
public class Euler034 extends AbstractEuler {

	private static final int[] factorials = new int[10];
	static {
		for (int i = 0; i <= 9; i++) {
			factorials[i] = factorial(i).intValue();
		}
	}
	
	@Override
	public Number calculate() {
		int answer = 0;
		//7 * 9! < 9999999, so the former is our upper bound
		for (int i = 0; i <= 7 * factorials[9]; i++) {
			if (isCurious(i)) answer += i;
		}
		return answer;
	}
	
	private boolean isCurious(long n) {
		if (n < 3) return false;
		long sumTotal = 0;
		for (String digit : String.valueOf(n).split("")) {
			if (!"".equals(digit)) {
				sumTotal += factorials[Integer.valueOf(digit)];
			}
			if (sumTotal > n) return false; //bail early if it's no use
		}
		return sumTotal == n;
	}

	@Override
	protected Number getCorrectAnswer() {
		return 40730;
	}

}
